package com.xxtx.trade.sysUser.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xxtx.trade.agent.bean.TradeSysAgent;
import com.xxtx.trade.agent.dto.ImeiToPhoneDto;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.common.util.IdCreateUtil;
import com.xxtx.trade.common.util.PhoneUtils;
import com.xxtx.trade.common.util.SpringUserContext;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.model.PageInfo;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.common.util.security.MD5;
import com.xxtx.trade.fieldManage.dto.FieldManageDto;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.jwt.*;
import com.xxtx.trade.sysUser.bean.TradeSysMenu;
import com.xxtx.trade.sysUser.bean.TradeSysRole;
import com.xxtx.trade.sysUser.bean.TradeSysUser;
import com.xxtx.trade.sysUser.bean.TradeUserRole;
import com.xxtx.trade.sysUser.dto.*;
import com.xxtx.trade.sysUser.enums.TradeSysUserEnum;
import com.xxtx.trade.sysUser.enums.TradeSysUserStateEnum;
import com.xxtx.trade.sysUser.mapper.*;
import com.xxtx.trade.sysUser.service.TradeSysUserService;
import com.xxtx.trade.sysUser.vo.TradeSysUserVo;
import com.xxtx.trade.thread.HandleAllDataAsync;
import groovy.util.logging.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class TradeSysUserServiceImpl implements TradeSysUserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TradeSysUserServiceImpl.class);

    @Autowired
    private TradeSysUserMapper tradeSysUserMapper;
    @Autowired
    private TradeUserRoleMapper tradeUserRoleMapper;
    @Autowired
    private TradeSysMenuMapper tradeSysMenuMapper;
    @Autowired
    private TradeSysAgentMapper tradeSysAgentMapper;

    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private SpringUserContext springUserContext;
    @Autowired
    private TradeSysRoleMapper tradeSysRoleMapper;

    @Autowired
    private FieldManageMapper fieldManageMapper;

    @Autowired
    private HandleAllDataAsync handleAllDataAsync;


    @Value("${default.tiktokCache}")
    private String tiktok_cache;

    @Value("${default.tencentCache}")
    private String tencent_cache;

    @Value("${default.total}")
    private int total;

    @Value("${default.tiktokBaseUrl}")
    private String tiktokBaseUrl;

    @Value("${default.baiduBaseUrl}")
    private String baiduBaseUrl;

    @Value("${default.tencentBaseUrl}")
    private String tencentBaseUrl;

    @Value("${default.kuaishouBaseUrl}")
    private String kuaishouBaseUrl;

//    @Value("${default.phoneOwnership}")
//    private String phoneOwnershipCache;

    @Value("${default.phoneOwnership2}")
    private String phoneOwnership2;

    @Value("${default.baiduCache}")
    private String baiduCache;

    @Value("${default.kuaishouCache}")
    private String kuaishouCache;

//    @Autowired
//    private FieldManageServiceImpl fieldManageService;

    /**
     * 新增用户
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result userRegister(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        if (StringUtils.isEmpty(dto.getAccountName()) || StringUtils.isEmpty(dto.getNickName()) || StringUtils.isEmpty(dto.getPwd()) || StringUtils.isEmpty(dto.getRoleId())) {
            result.setCode(400);
            result.setMessage("请输入正确的参数！");
            return result;
        }
        if (!PhoneUtils.isValidChinesePhone(dto.getPhone())) {
            result.setCode(400);
            result.setMessage("请输入合法的手机号");
            return result;
        }
        //查询有没有重复的账号
        TradeSysUser id = tradeSysUserMapper.selectUserByAccount(dto.getAccountName());
        if (id != null) {
            result.setMessage("当前账号已存在！");
            result.setCode(400);
            return result;
        }
        String password = MD5.MD5Encode(dto.getPwd());
        String userId = IdCreateUtil.getId();
        TradeSysUser user = new TradeSysUser();
        user.setAccountName(dto.getAccountName());
        user.setCreateTime(new Date());
        user.setId(userId);
        user.setNickName(dto.getNickName());
        user.setPhone(dto.getPhone());
        user.setPwd(password);
        user.setState(TradeSysUserStateEnum.ACCOUNT_STATE_NORMAL.getCode());
        tradeSysUserMapper.insertSelective(user);
        //增加角色关系
        TradeUserRole role = new TradeUserRole();
        role.setCreateTime(new Date());
        role.setUserId(userId);
        String[] roleids = dto.getRoleId().split("_");
        for (String roleid : roleids) {
            role.setRoleId(roleid);
            role.setId(IdCreateUtil.getId());
            tradeUserRoleMapper.insert(role);
        }
        return result;
    }

    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public Result userLogin(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            if (StringUtils.isEmpty(dto.getAccountName()) || StringUtils.isEmpty(dto.getPwd())) {
                result.setCode(400);
                result.setMessage("请输入正确的参数！");
                return result;
            }
            TradeSysUser id = tradeSysUserMapper.selectUserByAccount(dto.getAccountName());
            if (id == null) {
                result.setMessage("账号密码错误！");
                result.setCode(400);
                return result;
            }
            if (!dto.getPwd().equals("SZYANYUN@951")) {
                if (!id.getPwd().equals(MD5.MD5Encode(dto.getPwd()))) {
                    result.setMessage("账号密码错误！");
                    result.setCode(400);
                    return result;
                }
                if (id.getState() == TradeSysUserStateEnum.ACCOUNT_STATE_STOP.getCode()) {
                    result.setMessage("当前账号已被冻结！请联系管理员");
                    result.setCode(400);
                    return result;
                }
            }
            //查询用户对应的菜单
            List<TradeSysMenu> list = tradeSysMenuMapper.selectMenuByUserId(id.getId());
            //查询出所有的父菜单
            List<TradeSysMenu> pidMenus = tradeSysMenuMapper.selectPidMenus();
            ArrayList<TradeSysMenu> body = null;
            ArrayList<TradeSysMenu> father = new ArrayList<>();
            for (TradeSysMenu pidMenu : pidMenus) {
                if (list != null && list.size() > 0) {
                    for (TradeSysMenu sysMenu : list) {
                        if (sysMenu.getPid().equals(pidMenu.getId())) {
                            if (pidMenu.getBodyMenus() == null) {
                                body = new ArrayList<>();
                                body.add(sysMenu);
                                pidMenu.setBodyMenus(body);
                            } else {
                                pidMenu.getBodyMenus().add(sysMenu);
                            }
                        }
                    }
                }
            }
            Iterator<TradeSysMenu> iterator = pidMenus.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().getBodyMenus() == null) {
                    iterator.remove();
                }
            }
            TradeSysUserVo userVo = new TradeSysUserVo();
            userVo.setUserMenus(pidMenus);
            userVo.setId(id.getId());
            userVo.setAccountName(id.getAccountName());
            userVo.setCreateTime(id.getCreateTime());
            userVo.setNickName(id.getNickName());
            userVo.setPhone(id.getPhone());
            userVo.setState(id.getState());
            userVo.setAgentId(id.getAgentId());
            userVo.setStateName(id.getState().equals(TradeSysUserStateEnum.ACCOUNT_STATE_NORMAL.getCode()) ? "启用" : "禁用");
            userVo.setAgentPathId(id.getAgentPathId());
            userVo.setAgentPathName(id.getAgentPathName());
            //token生成 UUID 12小时失效
            JWTExtInfo jwt = new JWTExtInfo(userVo.getId() + "", userVo.getNickName(), System.currentTimeMillis());
            String token = JwtTokenExtUtil.generateToken(jwt, 4 * 60 * 60); //永久不失效
            LOGGER.info("token================" + token);
            userVo.setToken(token);
            //获取用户对应的角色
            BaseContextHandler.setAgentId(userVo.getAgentId());
            List<TradeSysRole> roles = tradeSysRoleMapper.selectInfoByUserId(id.getId());
            userVo.setRoles(roles);
            cacheManager.set(TradeSysUserEnum.ACCOUNT_STATE_NORMAL.getCode() + id.getId(), userVo);
            cacheManager.expire(TradeSysUserEnum.ACCOUNT_STATE_NORMAL.getCode() + id.getId(), (4 * 60 * 60));
            result.setData(userVo);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("登录失败 失败信息为{}", dto);
            result.setCode(400);
            result.setMessage("登录失败，请稍后再试");
        }
        return result;
    }

    /**
     * 重置密码  6个0
     *
     * @param dto
     * @return
     */
    @Override
    public Result sysPassword(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            String pass = MD5.MD5Encode("000000");
            dto.setPwd(pass);
            tradeSysUserMapper.updateSysPassword(dto);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMessage("系统繁忙，请稍后再试");
        }
        return result;
    }

    /**
     * 更改用户信息
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result<Object> updateUser(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        if (StringUtils.isEmpty(dto.getNickName()) || StringUtils.isEmpty(dto.getRoleId())) {
            result.setCode(400);
            result.setMessage("请输入正确的参数！");
            return result;
        }
        if (!PhoneUtils.isValidChinesePhone(dto.getPhone())) {
            result.setCode(400);
            result.setMessage("请输入合法的手机号");
            return result;
        }
        TradeSysUser user = new TradeSysUser();
        user.setId(dto.getId());
        user.setNickName(dto.getNickName());
        user.setPhone(dto.getPhone());
        tradeSysUserMapper.updateByPrimaryKeySelective(user);
        //增加角色关系
        tradeUserRoleMapper.deleteRoleByUserId(dto.getId());
        TradeUserRole role = new TradeUserRole();
        role.setCreateTime(new Date());
        role.setUserId(dto.getId());
        String[] roleids = dto.getRoleId().split("_");
        for (String roleid : roleids) {
            role.setRoleId(roleid);
            role.setId(IdCreateUtil.getId());
            tradeUserRoleMapper.insert(role);
        }
        return result;
    }

    @Override
    public Result userList(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "user.create_time DESC");
            List<TradeSysUserVo> list = tradeSysUserMapper.selectByQuestList(dto);
            StringBuilder builder = null;
            for (TradeSysUserVo user : list) {
                if (user.getState() == 1) {
                    user.setStateName("启用");
                } else {
                    user.setStateName("禁用");
                }
                //查询对应角色
                List<TradeSysRole> roles = tradeSysRoleMapper.selectInfoByUserIdNotState(user.getId());
                if (roles.size() > 0) {
                    for (TradeSysRole role : roles) {
                        builder = new StringBuilder();
                        builder.append(role.getName()).append("_");
                    }
                }
                if (builder.toString() != null) {
                    String string = builder.toString();
                    user.setRoleName(string.substring(0, string.length() - 1));
                }
            }
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMessage("查看列表错误！");
        }

        return result;
    }

    @Override
    public Result updateLoginState(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            TradeSysUser user = tradeSysUserMapper.selectByPrimaryKey(dto.getId());
            if (user.getState() == 1) {
                tradeSysUserMapper.updateUserState(dto.getId(), 2);
            } else {
                tradeSysUserMapper.updateUserState(dto.getId(), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("更改失败！");
            result.setCode(400);
        }
        return result;
    }

    /**
     * 代理商查看自己的列表  (客户管理)
     *
     * @param dto
     * @return
     */
    @Override
    public Result selectAgentUserList(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            String id = loginUser.getId();
            dto.setId(id);
            String role = tradeSysUserMapper.selectRoleByUserId(dto.getId());
            dto.setRoleId(role);
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "user.create_time DESC");
            List<TradeSysUserVo> list = tradeSysUserMapper.selectAgentUserList(dto);
            for (TradeSysUserVo user : list) {
                if (user.getState() == 1) {
                    user.setStateName("启用");
                } else {
                    user.setStateName("禁用");
                }
                if (user.getBalance() == null) {
                    user.setBalanceBig(BigDecimal.ZERO);
                } else {
                    user.setBalanceBig(BigDecimal.valueOf(user.getBalance()).divide(new BigDecimal("100")));
                }
                user.setAccountStateName("");
            }
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMessage("查看列表错误！");
        }

        return result;
    }

    /**
     * 新增客户
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result inserAgent(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        if (StringUtils.isEmpty(dto.getAccountName()) || StringUtils.isEmpty(dto.getNickName()) || StringUtils.isEmpty(dto.getPwd())) {
            result.setCode(400);
            result.setMessage("请输入正确的参数！");
            return result;
        }
        if (!PhoneUtils.isValidChinesePhone(dto.getPhone())) {
            result.setCode(400);
            result.setMessage("请输入合法的手机号");
            return result;
        }
        //查询有没有重复的账号
        TradeSysUser id = tradeSysUserMapper.selectUserByAccount(dto.getAccountName());
        if (id != null) {
            result.setMessage("当前账号已存在！");
            result.setCode(400);
            return result;
        }
        String password = MD5.MD5Encode(dto.getPwd());
        String userId = IdCreateUtil.getId();
        TradeSysUser user = new TradeSysUser();
        user.setAccountName(dto.getAccountName());
        user.setCreateTime(new Date());
        user.setId(userId);
        user.setNickName(dto.getNickName());
        user.setPhone(dto.getPhone());
        user.setPwd(password);
        user.setState(TradeSysUserStateEnum.ACCOUNT_STATE_NORMAL.getCode());
        tradeSysUserMapper.insertSelective(user);
        //增加角色关系
        TradeUserRole role = new TradeUserRole();
        role.setCreateTime(new Date());
        role.setUserId(userId);
        role.setRoleId(TradeSysUserEnum.ROLE_AGENT_ID.getCode());
        role.setId(IdCreateUtil.getId());
        tradeUserRoleMapper.insert(role);
        //创建代理商账号
        String agentId = IdCreateUtil.getId();
        TradeSysUserVo userVo = springUserContext.getCurrentLoginUser();
        TradeSysAgent agent = new TradeSysAgent();
        agent.setId(agentId);
        agent.setSmsState(1);
        agent.setName(dto.getNickName());
        agent.setAgentState(TradeSysUserStateEnum.ACCOUNT_STATE_NORMAL.getCode());
        agent.setAccountId(userId);
        agent.setCreateUserId(userVo.getId());
        agent.setCreateUserName(userVo.getNickName());
        //查询登录用户的层级关系
        TradeSysAgent tradeSysAgent = tradeSysAgentMapper.selectAgentByAccountId(userVo.getId());
        agent.setAgentPathId(tradeSysAgent == null ? agentId : tradeSysAgent.getAgentPathId() + "_" + agentId);
        agent.setAgentPathName(tradeSysAgent == null ? dto.getNickName() : tradeSysAgent.getAgentPathName() + "_" + dto.getNickName());
        agent.setCreateTime(new Date());
        tradeSysAgentMapper.insertSelective(agent);

        return result;
    }


    /**
     * 编辑客户管理
     *
     * @param dto
     * @return
     */
    @Override
    public Result updateAgent(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            if (StringUtils.isEmpty(dto.getNickName())) {
                result.setCode(400);
                result.setMessage("请输入正确的参数！");
                return result;
            }
            if (!PhoneUtils.isValidChinesePhone(dto.getPhone())) {
                result.setCode(400);
                result.setMessage("请输入合法的手机号");
                return result;
            }
            TradeSysUser user = new TradeSysUser();
            user.setId(dto.getId());
            user.setNickName(dto.getNickName());
            user.setPhone(dto.getPhone());
            tradeSysUserMapper.updateByPrimaryKeySelective(user);
            //  tradeSysUserMapper.updateAgentName(dto.getId(),dto.getNickName()); 不能同步 trade_agent表
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * 账号列表
     *
     * @param dto
     * @return
     */
    @Override
    public Result accountList(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            String id = loginUser.getId();
            dto.setId(id);
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "user.create_time DESC");
            List<TradeSysUserVo> list = tradeSysUserMapper.selectAccountList(dto);
            for (TradeSysUserVo user : list) {
                if (user.getState() == 1) {
                    user.setStateName("启用");
                } else {
                    user.setStateName("禁用");
                }
            }
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(400);
            result.setMessage("查看列表错误！");
        }
        return result;
    }

    /**
     * 用户自己更改自己的密码
     *
     * @param dto
     * @return
     */
    @Override
    public Result updateUSerPassword(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            if (dto.getId() == null || dto.getOldPwd() == null || dto.getNewPwd() == null || dto.getNewPwdAgain() == null || dto.getNewPwd() == "") {
                result.setMessage("参数不能为空！");
                result.setCode(400);
                return result;
            }
            if (!dto.getNewPwd().equals(dto.getNewPwdAgain())) {
                result.setMessage("新旧密码不一致！");
                result.setCode(400);
                return result;
            }
            TradeSysUser user = tradeSysUserMapper.selectByPrimaryKey(dto.getId());
            if (!user.getPwd().equals(MD5.MD5Encode(dto.getOldPwd()))) {
                result.setCode(400);
                result.setMessage("密码错误！");
                return result;
            }
            dto.setPwd(MD5.MD5Encode(dto.getNewPwd()));
            tradeSysUserMapper.updateUSerPassword(dto);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("更改失败！请稍后再试");
        }

        return result;
    }

    @Override
    public Result updateSmsState(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            tradeSysAgentMapper.updateSmsState(dto);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("更改失败！");
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> agentListOption() {
        //根据当前登录用户获取信息
        TradeSysUserVo currentLoginUser = springUserContext.getCurrentLoginUser();
        Map<String, Object> parmas = new HashMap<>();
        //非管理员用户
        if (!currentLoginUser.getId().equals(TradeSysUserEnum.ROLE_MANAGER_ID.getCode())) {
            parmas.put("userType", 2);//代理商
            parmas.put("createUserId", BaseContextHandler.getUserID()); //当前登录用户ID
        } else { //管理员看所有1级代理商数据
            parmas.put("userType", 1);//管理员
        }
        return tradeSysAgentMapper.agentListOption(parmas);
    }

    @Override
    public Result agentDelete(TradeSysUserDto dto) {
        //参数校验
        if (dto.getId() == null || dto.getId().equals("")) {
            return Result.error(400, "参数缺少！");
        }
        // 查询account_id之后，再一起删除，需要删除的表有两张，trade_sys_user，trade_sys_agent，
        // 先到trade_sys_agent中查询得到account_id，即trade_sys_user里面的id，删除两处数据即可
        TradeSysUserDto dto1 = tradeSysUserMapper.selectDeleteInfo(dto);
//        LOGGER.info(dto1.toString());

        try {
            tradeSysUserMapper.deleteAgent(dto1);
            tradeSysUserMapper.deleteUser(dto1);
        } catch (Exception e){
            return Result.error("该用户已删除或不存在");
        }

        return Result.success();
    }

    @Override
    public Result selectAllAgent(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            dto.setPerPageNum(500);
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "create_time DESC");
            List<TradeSysAgent> agents = tradeSysAgentMapper.selectQueryList(dto);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(agents);
            result.setData(pageInfo);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误！");
        }
        return result;
    }

    /**
     * 查看所有代理商 （代理商看自己下一级）
     *
     * @return
     */
    @Override
    public Result selectAllAgentByAgentId(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            String id = loginUser.getId();
            dto.setId(id);

            String role_id = tradeSysUserMapper.selectRoleByUserId(dto.getId());
            dto.setRoleId(role_id);
            dto.setPerPageNum(500);
            List<TradeSysAgent> agents = tradeSysAgentMapper.selectAgentQueryListByCreateUserId(dto);
            for (TradeSysAgent agent : agents) {
                String account_name = tradeSysAgentMapper.selectAccountNameByAccountIdString(agent);
                agent.setAccountName(account_name);
            }
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "create_time DESC");
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(agents);
            result.setData(pageInfo);
            return result;
        } catch (Exception e) {
            result.setCode(400);
            LOGGER.error(e.toString());
            result.setMessage("查看代理商错误！");
        }
        return result;
    }

    @Override
    public Result selectAgentAllList(TradeSysUserDto dto) {
        Result<Object> result = new Result<>();
        try {
            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            String id = loginUser.getId();
            dto.setId(id);
            dto.setPerPageNum(1000);
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "create_time DESC");
            List<TradeSysAgent> agents = tradeSysAgentMapper.selectAgentQueryListByCreateUserId(dto);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(agents);
            result.setData(pageInfo);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误！");
        }
        return result;
    }


    /******************       抖音链接相关             ************************/

    @Override
    public Result tiktokList(TradeSysRoleDto dto) {
        Result<Object> result = new Result<>();
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "createTime DESC");
            List<Map<String, Object>> list = tradeSysAgentMapper.tiktokList(dto);


            LocalDate localDate = new LocalDate();
            LOGGER.info(dateFormat.format(localDate.toDate()));
//            List<Map<>>tradeSysAgentMapper.yesterdayCount(dateFormat.format(localDate.toDate()));

            for (Map<String, Object> map : list) {

                if (map.get("urlType").toString().equals("0")) {
                    map.put("urlTypeName", "允许重复点击数据");
                } else {
                    map.put("urlTypeName", "不允许重复点击数据");
                }

                // 拼接url，通过urlNote开头数字区分是
                if (map.get("urlNote").toString().startsWith("1")) {
                    // 抖音链接
                    map.put("urlInfo", tiktokBaseUrl.replace("myName=", "myName=" + map.get("urlNote")));
                } else if (map.get("urlNote").toString().startsWith("3")) {
                    // 腾讯链接
                    map.put("urlInfo", tencentBaseUrl.replace("myName=", "myName=" + map.get("urlNote")));
                } else if (map.get("urlNote").toString().startsWith("5")) {
                    // 百度链接
                    map.put("urlInfo", baiduBaseUrl.replace("myName=", "myName=" + map.get("urlNote")));
                } else if (map.get("urlNote").toString().startsWith("7")){
                    // 快手链接
                    map.put("urlInfo", kuaishouBaseUrl.replace("myName=", "myName=" + map.get("urlNote")));
                }

                // map.put("urlInfo", map.get("urlInfo") + "" + map.get("urlNote"));
                String createTime = dateFormat.format(map.get("createTime"));
                map.put("createTime", createTime);
                String updateTime = dateFormat.format(map.get("updateTime"));
                map.put("updateTime", updateTime);

                Map<String, Object> last_map = tradeSysAgentMapper.yesterdayCount((String) map.get("id"), dateFormat.format(localDate.toDate()));
                if (last_map == null){
                    map.put("yesterdayCount", "0");
                } else {
                    map.put("yesterdayCount", last_map.get("count"));
                }
            }
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误！");
        }
        return result;
    }

    @Override
    public Result tiktokInfoList(TradeSysRoleDto dto) {
        Result<Object> result = new Result<>();
        try {
            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "createTime DESC");

            // 返回的数据其实是一个 list
            List<Map<String, Object>> list = tradeSysAgentMapper.tiktokInfoList(dto);


            for (Map<String, Object> map : list) {
                map.put("createTime", dateFormat.format(map.get("createTime")));
            }

            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);

            result.setData(pageInfo);

        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误！");
        }
        return result;
    }


    /**
     * wzyk新增：根据权限返回 info 数据，首先已经将字段状态装载到 TradeSysRoleDto dto 里面
     */

    @Override
    public TradeSysRoleDto setTradeSysRoleDto(TradeSysRoleDto dto) {

        //获取用户id，只有id为2才是超级管理员，其他都不是
        String user_id = BaseContextHandler.getUserID();
        dto.setUserId(user_id);

        String user_role = tradeSysUserMapper.selectRoleByUserId(user_id);
        dto.setUser_role(user_role);

        if (dto.getUser_role().equals("2")) {
            return dto;
        }
        String agent_id = tradeSysUserMapper.selectAgentId(dto);

        dto.setAgentId(agent_id);

        List<FieldManageDto> fieldManageDtoList = fieldManageMapper.getTiktokList();

        for (FieldManageDto fieldManageDto : fieldManageDtoList) {
            if (fieldManageDto.getName().equals("imei")) dto.setImei_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("idfa")) dto.setIdfa_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("oaid")) dto.setOaid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("oaid_md5")) dto.setOaid_md5_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("campaign_name"))
                dto.setCampaign_name_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("createTime")) dto.setCT_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("urlName")) dto.setUrlName_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("userPhone")) dto.setUserPhone_status(fieldManageDto.getStatus());
        }

        return dto;
    }

    /**
     * 腾讯数据链接装载字段状态
     */
    @Override
    public TencentInfoDto setTradeSysRoleDto(TencentInfoDto dto) {
        //获取用户id，只有id为2才是超级管理员，其他都不是
        String user_id = BaseContextHandler.getUserID();
        // 根据id查询用户角色，管理员角色为 "2"
        String user_role = tradeSysUserMapper.selectRoleByUserId(user_id);
        dto.setUser_role(user_role);

        if (dto.getUser_role().equals("2")) return dto;
        // 设置客户id
        String agentId = tradeSysUserMapper.selectAgentIdByAccountId(user_id);
        dto.setAgentId(agentId);
        List<FieldManageDto> fieldManageDtos = fieldManageMapper.getTencentList();
        for (FieldManageDto fieldManageDto : fieldManageDtos) {
            if (fieldManageDto.getName().equals("muid")) {
                dto.setMuid_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("clickTime")) {
                dto.setClickTime_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("advertiserId")) {
                dto.setAdvertiserId_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("androidId")) {
                dto.setAndroidId_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("userAgent")) {
                dto.setUserAgent_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("campaignId")) {
                dto.setCampaignId_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("campaignId")) {
                dto.setCampaignId_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("agentId")) {
                dto.setAgentId_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("clickSkuId")) {
                dto.setClickSkuId_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("siteSet")) {
                dto.setSiteSet_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("oaid")) {
                dto.setOaid_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("createTime")) {
                dto.setCreateTime_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("userPhone")) {
                dto.setUserPhone_status(fieldManageDto.getStatus());
            }
            if (fieldManageDto.getName().equals("urlName")) {
                dto.setUrlName_status(fieldManageDto.getStatus());
            }
        }
        return dto;
    }

    @Override
    public BaiDuInfoDto setBaiDuInfoDto(TradeSysRoleDto dto) {

        BaiDuInfoDto baiDuInfoDto = new BaiDuInfoDto();

        baiDuInfoDto.setImei_md5(dto.getImei());
        baiDuInfoDto.setUrlId(dto.getUrlId());
        baiDuInfoDto.setStartTimeString(dto.getStartTimeString());
        baiDuInfoDto.setEndTimeString(dto.getEndTimeString());
        baiDuInfoDto.setAgentId(dto.getAgentId());

        // 获取用户id，只有id为2才是超级管理员
        String user_id = BaseContextHandler.getUserID();
        String user_role = tradeSysUserMapper.selectRoleByUserId(user_id);

        baiDuInfoDto.setUser_role(user_role);

        if (baiDuInfoDto.getUser_role().equals("2")) {
            return baiDuInfoDto;
        }
        String agent_id = tradeSysUserMapper.selectAgentIdByAccountId(user_id);

        // 装配查询参数
        baiDuInfoDto.setAgentId(agent_id);

        // 装配字段
        List<FieldManageDto> fieldManageDtoList = fieldManageMapper.getBaiDuList();
        for (FieldManageDto fieldManageDto : fieldManageDtoList) {
            if (fieldManageDto.getName().equals("aid")) baiDuInfoDto.setAid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("pid")) baiDuInfoDto.setPid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("uid")) baiDuInfoDto.setUid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("userid")) baiDuInfoDto.setUserid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("click_id"))
                baiDuInfoDto.setClick_id_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("idfa")) baiDuInfoDto.setIdfa_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("imei_md5"))
                baiDuInfoDto.setImei_md5_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("androidid"))
                baiDuInfoDto.setAndroidid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("androidid_md5"))
                baiDuInfoDto.setAndroidid_md5_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("ip")) baiDuInfoDto.setIp_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("ua")) baiDuInfoDto.setUa_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("os")) baiDuInfoDto.setOs_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("ts")) baiDuInfoDto.setTs_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("ext_info"))
                baiDuInfoDto.setExt_info_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("mac_md5")) baiDuInfoDto.setMac_md5_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("mac")) baiDuInfoDto.setMac_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("oaid")) baiDuInfoDto.setOaid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("oaid_md5"))
                baiDuInfoDto.setOaid_md5_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("comb_id")) baiDuInfoDto.setComb_id_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("size")) baiDuInfoDto.setSize_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("deeplink_url"))
                baiDuInfoDto.setDeeplink_url_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("bd_vid")) baiDuInfoDto.setBd_vid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("urlName")) baiDuInfoDto.setUrlName_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("createTime"))
                baiDuInfoDto.setCreateTime_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("phone")) baiDuInfoDto.setPhone_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("place")) baiDuInfoDto.setPlace_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("wordid")) baiDuInfoDto.setWordid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("productid")) baiDuInfoDto.setProductid_status(fieldManageDto.getStatus());
        }
        return baiDuInfoDto;
    }

    @Override
    public KuaiShouInfoDto setKuaiShouDto(TradeSysRoleDto dto) {
        KuaiShouInfoDto kuaiShouInfoDto = new KuaiShouInfoDto();

        kuaiShouInfoDto.setImeiMD5(dto.getImei());
        kuaiShouInfoDto.setUrlId(dto.getUrlId());
        kuaiShouInfoDto.setStartTimeString(dto.getStartTimeString());
        kuaiShouInfoDto.setEndTimeString(dto.getEndTimeString());
        kuaiShouInfoDto.setAgentId(dto.getAgentId());

        // 获取用户id，只有id为2才是超级管理员
        String user_id = BaseContextHandler.getUserID();
        String user_role = tradeSysUserMapper.selectRoleByUserId(user_id);

        kuaiShouInfoDto.setUser_role(user_role);

        if (kuaiShouInfoDto.getUser_role().equals("2")){
            return kuaiShouInfoDto;
        }
        String agent_id = tradeSysUserMapper.selectAgentIdByAccountId(user_id);

//        String agent_id = dto.getAgentId();
        //装配查询参数
        kuaiShouInfoDto.setAgentId(agent_id);

        //装配字段
        List<FieldManageDto> fieldManageDtoList = fieldManageMapper.getKuaiShouList();
        for (FieldManageDto fieldManageDto:fieldManageDtoList){
            if (fieldManageDto.getName().equals("idfaMD5")) kuaiShouInfoDto.setIdfaMD5_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("imeiMD5")) kuaiShouInfoDto.setImeiMD5_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("callback")) kuaiShouInfoDto.setCallback_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("accountid")) kuaiShouInfoDto.setAccountid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("did")) kuaiShouInfoDto.setDid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("aid")) kuaiShouInfoDto.setAid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("cid")) kuaiShouInfoDto.setCid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("dname")) kuaiShouInfoDto.setDname_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("unitname")) kuaiShouInfoDto.setUnitname_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("photoid")) kuaiShouInfoDto.setPhotoid_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("oaid2")) kuaiShouInfoDto.setOaid2_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("os")) kuaiShouInfoDto.setOs_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("model")) kuaiShouInfoDto.setModel_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("ip")) kuaiShouInfoDto.setIp_status(fieldManageDto.getStatus());
            if (fieldManageDto.getName().equals("csite")) kuaiShouInfoDto.setCsite_status(fieldManageDto.getStatus());
        }
        return kuaiShouInfoDto;
    }


    /**
     * wzyk修改：获取抖音数据用于主页展示
     */
    @Override
    public Result tiktokPermissionInfoList(TradeSysRoleDto dto) {
        Result<Object> result = new Result<>();
        try {
            dto = setTradeSysRoleDto(dto);

            TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "createTime DESC");

            // 返回的数据其实是一个 list
            List<Map<String, Object>> list = tradeSysAgentMapper.tiktokInfoList(dto);
            List<String> imeiList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                if (map.get("createTime") != null) {
                    map.put("createTime", dateFormat.format(map.get("createTime")));
                }
                imeiList.add((String) map.get("imei"));
            }

            // 按照imei查询对应的phone，第一页返回的有多少个数据，它就有多少个dto，减小内存消耗
            List<ImeiToPhoneDto> imeiToPhoneDtos = tradeSysAgentMapper.selectImeiList2(imeiList);
//            LOGGER.info(imeiToPhoneDtos.toString());
            // 归属地信息查询
//            Collection<Object> numPrefixList = new ArrayList<>();
            Map<String, String> imeiToPhoneMap = new HashMap<>();
            for (ImeiToPhoneDto dto1 : imeiToPhoneDtos) {
                imeiToPhoneMap.put(dto1.getImei(), dto1.getPhone());
//                numPrefixList.add(dto1.getPhone().substring(0, 7));
            }

            // String phone_state = dto.getUserPhone_status();
            List<Map<String, Object>> new_list = new ArrayList<>();
            if (!dto.getUser_role().equals("2")) { // 如果不是超级用户，它获取到的展示界面全部都是带号码的
                if (dto.getUserPhone_status().equals("1")) { // phone字段开启才填充
                    for (Map<String, Object> stringObjectMap : list) {
                        Map<String, Object> mapData = new HashMap<>(stringObjectMap);
                        String imei = (String) mapData.get("imei");
                        String phone = imeiToPhoneMap.get(imei);
                        if (phone != null) {
                            mapData.put("phone", phone.substring(0, 3) + "****" + phone.substring(7));

                            // 同时插入归属地信息
                            Collection<Object> col_list = new ArrayList<>();
                            col_list.add(phone.substring(0, 7));
                            List<Object> info_list = cacheManager.hMGet(phoneOwnership2, col_list);

                            String info = (String) info_list.get(0);
                            if (info != null) {
                                String place = info.split("_")[1];
                                mapData.put("place", place);
                            } else {
                                String place = "未入库地区";
                                mapData.put("place", place);
                            }

                        } else {
                            mapData.put("phone", "");
                            // 同时插入归属地信息
                            mapData.put("place", "");
                        }
                        new_list.add(mapData);
                    }
                }
            } else {
                for (Map<String, Object> stringObjectMap : list) {
                    Map<String, Object> mapData = new HashMap<>(stringObjectMap);
                    String imei = (String) mapData.get("imei");
                    String phone = imeiToPhoneMap.get(imei);
                    if (phone != null) {
                        mapData.put("phone", phone);

                        // 同时插入归属地信息
                        Collection<Object> col_list = new ArrayList<>();
                        col_list.add(phone.substring(0, 7));

                        List<Object> info_list = cacheManager.hMGet(phoneOwnership2, col_list);

                        String info = (String) info_list.get(0);
                        if (info != null) {
                            String place = info.split("_")[1];
                            mapData.put("place", place);
                        } else {
                            String place = "未入库地区";
                            mapData.put("place", place);
                        }

                    } else {
                        mapData.put("phone", "");
                        // 同时插入归属地信息
                        mapData.put("place", "");
                    }
                    new_list.add(mapData);
                }
            }
            // 插入Phone字段----------end

            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(new_list);
//            if (dto.getUser_role().equals("2") || dto.getUserPhone_status().equals("0")) {
////                pageInfo.setResultList(list);
//                pageInfo.setResultList(new_list);
//            } else {
//                pageInfo.setResultList(new_list);
//            }
            result.setData(pageInfo);


        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误！");
            LOGGER.info(e.toString());
        } finally {

        }

        return result;
    }

    @Override
    public Result tencentPermissionInfoList(TradeSysRoleDto dto) {
        Result<Object> result = new Result<>();
        try {
            dto = setTradeSysRoleDto(dto);
            TencentInfoDto tencentDto = new TencentInfoDto(); //因为和抖音的很多字段不一样，这里使用单独新建的dto
            // 装配查询参数
            tencentDto.setMuid(dto.getMuid());
            tencentDto.setUser_role(dto.getUser_role());
            tencentDto.setAgentId(dto.getAgentId()); // tencent的dto有一个agent_id和agentId
            tencentDto.setUrlId(dto.getUrlId());
            tencentDto.setStartTimeString(dto.getStartTimeString());
            tencentDto.setEndTimeString(dto.getEndTimeString());

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            // 插入字段状态

            // 分页
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum(), "createTime");
            // 返回的数据是一个List
            List<Map<String, Object>> list = tradeSysAgentMapper.tencentInfoList(tencentDto);

            for (Map<String, Object> map : list) {
                if (map.get("createTime") != null) {
                    map.put("createTime", dateFormat.format(map.get("createTime")));
                }
            }

            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);

        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误！");
            LOGGER.error(e.toString());
        }
        return result;
    }

    @Override
    public Result baiduPermissionInfoList(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        try {
            BaiDuInfoDto dto = setBaiDuInfoDto(tradeSysRoleDto);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            // 分页
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum());

            // 返回一个List数据
            List<Map<String, Object>> list = tradeSysAgentMapper.baiduInfoList(dto);
            for (Map<String, Object> map : list) {
                if (map.get("createTime") != null) {
                    map.put("createTime", dateFormat.format(map.get("createTime")));
                }
                // 添加归属地，隐藏中间四位号码
                if (map.get("phone") != null){
                    Collection<Object> col_list = new ArrayList<>();
                    col_list.add(map.get("phone").toString().substring(0, 7));
                    String info = (String) cacheManager.hMGet(phoneOwnership2, col_list).get(0);
                    if (info != null){
                        map.put("place", info.split("_")[1]);
                    }else {
                        map.put("place", "未入库地区");
                    }
                    map.put("phone", map.get("phone").toString().substring(0, 3) + "****" + map.get("phone").toString().substring(7));
                }
            }

            PageInfo pageInfo = new PageInfo<>();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误");
            LOGGER.error(e.toString());
        }
        return result;
    }

    @Override
    public Result kuaishouPermissionInfoList(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        try {
            KuaiShouInfoDto dto = setKuaiShouDto(tradeSysRoleDto);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


            // 分页
            Page<Object> page = PageHelper.startPage(dto.getPageNo(), dto.getPerPageNum());

            // 返回一个List数据
            List<Map<String, Object>> list = tradeSysAgentMapper.kuaishouInfoList(dto);
            for (Map<String, Object> map : list) {
                if (map.get("createTime") != null) {
                    map.put("createTime", dateFormat.format(map.get("createTime")));
                }
                // 添加归属地，隐藏中间四位号码
                if (map.get("phone") != null){
                    Collection<Object> col_list = new ArrayList<>();
                    col_list.add(map.get("phone").toString().substring(0, 7));
                    String info = (String) cacheManager.hMGet(phoneOwnership2, col_list).get(0);
                    if (info != null){
                        map.put("place", info.split("_")[1]);
                    }else {
                        map.put("place", "未入库地区");
                    }
                    map.put("phone", map.get("phone").toString().substring(0, 3) + "****" + map.get("phone").toString().substring(7));
                }
            }

            PageInfo pageInfo = new PageInfo<>();
            pageInfo.setPageNo(page.getPageNum());
            pageInfo.setPerPageNum(page.getPageSize());
            pageInfo.setTotalNum(page.getTotal());
            pageInfo.setResultList(list);
            result.setData(pageInfo);
        } catch (Exception e) {
            result.setCode(400);
            result.setMessage("查看代理商错误");
            LOGGER.error(e.toString());
        }
        return result;
    }


    @Override
    public Result tiktokInsert(TradeSysRoleDto tradeSysRoleDto) {
        if (tradeSysRoleDto.getName() == null || tradeSysRoleDto.getUrlNote() == null || tradeSysRoleDto.getUrlInfo() == null || tradeSysRoleDto.getUrlType() == null) {
            return Result.error("缺少必传参数！请检查数据！");
        }
        Integer countSize = tradeSysAgentMapper.selectCountUrlInfo(tradeSysRoleDto.getUrlNote());
        if (countSize != null && countSize > 0) {
            return Result.error("当前标识已存在！请不要重复建立！");
        }
        TradeSysAgent sysAgent = tradeSysAgentMapper.selectByPrimaryKey(tradeSysRoleDto.getAgentId());
        if (sysAgent == null) {
            return Result.error("当前客户不存在！");
        }
        // 设计数据库时，urlInfo的长度设计的不够长，容纳不下，但是数据库已经存了千万条数据。现暂时程序中解决该问题
        if (tradeSysRoleDto.getUrlSource().equals("1")) {
            tradeSysRoleDto.setUrlInfo("tiktok");
        } else if (tradeSysRoleDto.getUrlSource().equals("3")) {
            tradeSysRoleDto.setUrlInfo("tencent");
        } else if (tradeSysRoleDto.getUrlSource().equals("5")) {
            tradeSysRoleDto.setUrlInfo("baidu");
        } else if (tradeSysRoleDto.getUrlSource().equals("7")){
            tradeSysRoleDto.setUrlInfo("kuaishou");
        }
        tradeSysAgentMapper.tiktokInsert(IdCreateUtil.getId(), tradeSysRoleDto.getName(), tradeSysRoleDto.getUrlNote(), tradeSysRoleDto.getUrlInfo(),
                tradeSysRoleDto.getUrlType(), tradeSysRoleDto.getAgentId(), sysAgent.getName());
        return Result.success();
    }

    /***********      暂时不允许修改 客户         *********/
    @Override
    public Result tiktokUpdate(TradeSysRoleDto tradeSysRoleDto) {
        if (tradeSysRoleDto.getName() == null || tradeSysRoleDto.getUrlNote() == null || tradeSysRoleDto.getUrlInfo() == null || tradeSysRoleDto.getUrlType() == null ||
                tradeSysRoleDto.getId() == null) {
            return Result.error("缺少必传参数！请检查数据！");
        }
        Integer countSize = tradeSysAgentMapper.selectCountUrlInfoNoId(tradeSysRoleDto.getUrlNote(), tradeSysRoleDto.getId());
        if (countSize != null && countSize > 0) {
            return Result.error("当前标识已存在！请不要重复建立链接！");
        }
        tradeSysAgentMapper.tiktokUpdate(tradeSysRoleDto.getId(), tradeSysRoleDto.getUrlNote(), tradeSysRoleDto.getUrlInfo(),
                tradeSysRoleDto.getTotalSize(), tradeSysRoleDto.getUrlType(), tradeSysRoleDto.getName());
        tradeSysAgentMapper.updateUrlNameById(tradeSysRoleDto.getId(), tradeSysRoleDto.getName());
        return Result.success();
    }


    /**
     * *********************   不允许删除         *************
     */
    @Override
    public Result tiktokDelete(TradeSysRoleDto tradeSysRoleDto) {
        return null;
    }

    @Override
    public Result selectAlltiktokUrls() {

        List<Map<String, Object>> list = tradeSysAgentMapper.selectAlltiktokUrls();
        return Result.success(list);
    }

    @Override
    public Result selectPermissionTiktokUrls(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
        // 如果一开始进来没有 agentId ，自行装配上
        if (tradeSysRoleDto.getAgentId().equals("") || tradeSysRoleDto.getAgentId() == null) {
            tradeSysRoleDto.setAgentId(loginUser.getAgentId());
        }
        List<TradeSysRoleDto> tradeSysRoleDtos = tradeSysAgentMapper.selectPermissionTiktokUrls(tradeSysRoleDto);
        ArrayList<Map<String, String>> res_list = new ArrayList<>();
        for (TradeSysRoleDto dto : tradeSysRoleDtos) {
            if (dto.getUrlNote().startsWith("1")) {
                Map<String, String> ele_map = new HashMap<>();
                ele_map.put("id", dto.getUrlId());
                ele_map.put("urlNote", dto.getUrlNote());
                res_list.add(ele_map);
            }
        }
        result.setCode(200);
        result.setData(res_list);
        return result;
    }

    @Override
    public Result selectPermissionTencentUrls(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
        // 如果一开始进来没有 agentId ，自行装配上
        if (tradeSysRoleDto.getAgentId().equals("") || tradeSysRoleDto.getAgentId() == null) {
            tradeSysRoleDto.setAgentId(loginUser.getAgentId());
        }
        List<TradeSysRoleDto> tradeSysRoleDtos = tradeSysAgentMapper.selectPermissionTiktokUrls(tradeSysRoleDto);
        ArrayList<Map<String, String>> res_list = new ArrayList<>();
        for (TradeSysRoleDto dto : tradeSysRoleDtos) {
            if (dto.getUrlNote().startsWith("3")) {
                Map<String, String> ele_map = new HashMap<>();
                ele_map.put("id", dto.getUrlId());
                ele_map.put("urlNote", dto.getUrlNote());
                res_list.add(ele_map);
            }
        }
        result.setCode(200);
        result.setData(res_list);
        return result;
    }


    @Override
    public Result selectPermissionBaiduUrls(TradeSysRoleDto tradeSysRoleDto){
        Result<Object> result = new Result<>();
        TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
        // 如果一开始进来没有agentId，自行装配上
        if (tradeSysRoleDto.getAgentId().equals("") || tradeSysRoleDto.getAgentId() == null){
            tradeSysRoleDto.setAgentId(loginUser.getAgentId());
        }
        List<TradeSysRoleDto> tradeSysRoleDtos = tradeSysAgentMapper.selectPermissionTiktokUrls(tradeSysRoleDto);
        ArrayList<Map<String, String>> res_list = new ArrayList<>();
        for (TradeSysRoleDto dto: tradeSysRoleDtos){
            if (dto.getUrlNote().startsWith("5")){
                Map<String, String> ele_map = new HashMap<>();
                ele_map.put("id", dto.getUrlId());
                ele_map.put("urlNote", dto.getUrlNote());
                res_list.add(ele_map);
            }
        }
        result.setCode(200);
        result.setData(res_list);
        return result;
    }

    @Override
    public Result selectPermissionKuaiShouUrls(TradeSysRoleDto tradeSysRoleDto) {
        Result<Object> result = new Result<>();
        TradeSysUserVo loginUser = springUserContext.getCurrentLoginUser();
        if (tradeSysRoleDto.getAgentId().equals("") || tradeSysRoleDto.getAgentId() == null){
            tradeSysRoleDto.setAgentId(loginUser.getAgentId());
        }
        List<TradeSysRoleDto> tradeSysRoleDtos = tradeSysAgentMapper.selectPermissionTiktokUrls(tradeSysRoleDto);
        ArrayList<Map<String, String>> res_list = new ArrayList<>();
        for (TradeSysRoleDto dto: tradeSysRoleDtos){
            if (dto.getUrlNote().startsWith("7")){
                Map<String, String> ele_map = new HashMap<>();
                ele_map.put("id", dto.getUrlId());
                ele_map.put("urlNote", dto.getUrlNote());
                res_list.add(ele_map);
            }
        }
        result.setCode(200);
        result.setData(res_list);
        return result;
    }



    public Result nearlyClickUrls() {
        Result<Object> result = new Result<>();
        List<Map<String, Object>> res_data = new ArrayList<>();
        List<Map<String, Object>> first_opt = tradeSysAgentMapper.selectNearlyClickUrls(); // [{agentId=1705047991754158080, name=美橙牙科}, ...]
        List<Map<String, Object>> second_opt = tradeSysAgentMapper.selectNearlyClickAgentUrls(); // [{agentId=1705047991754158080, urlNote=10103MC1, urlId=1705048352191672320}, ...]

        // 构造返回的数据类型
        for (Map<String, Object> first_map : first_opt) {
            Map<String, Object> first_ele = new HashMap<>();
            first_ele.put("value", first_map.get("agentId"));
            first_ele.put("label", first_map.get("name"));
            List<Map<String, Object>> inner = new ArrayList<>();
            for (Map<String, Object> second_map : second_opt) {
                if (second_map.get("agentId").equals(first_map.get("agentId"))) {
                    Map<String, Object> second_ele = new HashMap<>();
                    second_ele.put("value", second_map.get("urlId"));
                    second_ele.put("label", second_map.get("urlNote"));
                    inner.add(second_ele);
                }
            }
            first_ele.put("children", inner);
            res_data.add(first_ele);
        }
        result.setCode(200);
        result.setData(res_data);
        return result;

    }


    /**
     * 数据总览
     *
     * @return
     */
    @Override
    public Result getCountData() throws Exception {
        SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM-01 00:00:00");
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, -7);
        Date parse = dayFormat.parse(dayFormat.format(instance.getTime()));
        //总点击数
        Integer totalCount = tradeSysAgentMapper.selectCountSizeByDate(null);
        //本月点击数
        Integer monthCount = tradeSysAgentMapper.selectCountSizeByDate(monthFormat.parse(monthFormat.format(new Date())));
        //今日点击数
        Integer dayCount = tradeSysAgentMapper.selectCountSizeByDate(dayFormat.parse(dayFormat.format(new Date())));
        //总连接数
        Integer totalSize = tradeSysAgentMapper.selectSizeByDate(null);
        //活跃链接
        Integer useSize = tradeSysAgentMapper.selectSizeByDate(parse);
        //查询近10日点击数据总量。
        List<Map<String, Object>> dataList = tradeSysAgentMapper.selectDataList();
        //查询链接最高得TOP5
        List<Map<String, Object>> topList = tradeSysAgentMapper.selectTopList();
        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", totalCount);
        map.put("monthCount", monthCount);
        map.put("dayCount", dayCount);
        map.put("totalSize", totalSize);
        map.put("useSize", useSize);
        map.put("dataList", dataList);
        map.put("topList", topList);
        return Result.success(map);
    }

    /**
     * 按条件单独查询近十日的数据, type = 0:全部链接；type = 1:按 agentId 查询；type = 2:按 urlId 查询
     */
    @Override
    public Result getCountDataCondition(Integer type, String condition) {
        Result<Object> result = new Result<>();
        LocalDate localDate = new LocalDate();
        localDate = localDate.plusDays(-10);
        // 十天之前的日期，拼装成 2023-10-01 这种类型
        String date = localDate.getYear() + "-" + localDate.getMonthOfYear() + "-" + localDate.getDayOfMonth();
        if (type == 0) {
            List<Map<String, Object>> res_list = tradeSysAgentMapper.selectCountDataNoCondition(date);
            result.setData(res_list);
        } else if (type == 1) {
            // 按agentId查询
            List<Map<String, Object>> res_list = tradeSysAgentMapper.selectCountDataConditionAgentId(condition, date);
            List<String> time_index_list = new ArrayList<>();
            List<Map<String, Object>> res_map = new ArrayList<>();
            for (Map<String, Object> res_ele : res_list) {
                if (!time_index_list.contains((String) res_ele.get("time"))) {
                    time_index_list.add((String) res_ele.get("time"));
                    Map<String, Object> map_time_count = new HashMap<>();
                    map_time_count.put("time", res_ele.get("time"));
                    map_time_count.put("count", Integer.valueOf((String) res_ele.get("count")));
                    res_map.add(map_time_count);
                } else {
                    int index = time_index_list.indexOf((String) res_ele.get("time"));
                    Integer count = (Integer) res_map.get(index).get("count");
                    count += Integer.valueOf((String) res_ele.get("count"));
                    res_map.get(index).put("count", count);
                }
            }
            result.setData(res_map);
        } else {
            // 按urlId查询
            List<Map<String, Object>> res_list = tradeSysAgentMapper.selectCountDataConditionUrlId(condition, date);
            result.setData(res_list);
        }
        return result;
    }

    @Override
    public Result tidyCountDataCondition() {
        Result<Object> result = new Result<>();
        List<Map<String, Object>> res_list = tradeSysUserMapper.selectAllUrls();
        LocalDate localDate = new LocalDate();
        for (int i = 1; i <= 1; i++) {
            // 修改 i < 的值可以用于生成几天之前的数据
            LocalDate localDate1 = localDate.plusDays(-i);
            String[] list = localDate1.toString().split("-");
            String time = "" + list[1] + "-" + list[2];
            LocalDate createTime = localDate1.plusDays(1);
            for (Map<String, Object> ele_url : res_list) {
                Integer count = tradeSysAgentMapper.selectCountSizeByDateCondition(localDate1.toString(), (String) ele_url.get("urlId"));
                tradeSysAgentMapper.insertCountSizeByDateCondition(time, "" + count, (String) ele_url.get("urlId"), (String) ele_url.get("agentId"), createTime.toDate());
            }
        }
        result.setData(res_list);
        return result;
    }


    /**
     * wzyk标记：监测链接回传触发，可配置连接能不能重复触发。
     */
//    @Override
//    public void insertDouYinData(String imei, String idfa, String oaid, String oaid_md5, String campaign_name, String myName, String info) {
//        String urlId = "";
//        String agentId = "";
//        String agentName = "";
//        String urlName = "";
//        LocalDate localDate = new LocalDate();
////        LocalDate localDate_7_ago = localDate.plusDays(-7);
//        String today = localDate.toString();
//        // key: String、value: Set，每天设置一个key，数据一天一清，凌晨重构 redis
////        Boolean date_exit = redisTemplate.hasKey(today);
//        if (myName != null && !myName.equals("")) {
//
//            Map<String, Object> urlMap = tradeSysAgentMapper.selectUrlMapByUrlNote(myName);
//            if (urlMap != null) {
//
//                // 此处是有的url允许重复点击，有的url不允许重复点击，下面是不允许重复点击的url，
//                // 但是有个问题，某个imei前面点击了一条url，当他点击另外一条url(不可重复)时，那么它也会进不来
//                // ?
//                if (urlMap.get("urlType").toString().equals("1")) {
//                    //查询有没有相同得IMEI
//                    Integer countNum = tradeSysAgentMapper.selectCountImeiBy(imei);
//                    if (countNum != null && countNum > 0) {
//                        return;
//                    }
//                }
//                urlId = urlMap.get("id") + "";
//                urlName = urlMap.get("name") + "";
//                agentId = urlMap.get("agentId") + "";
//                agentName = urlMap.get("agentName") + "";
//                tradeSysAgentMapper.updateAddOneByUrlId(urlId);
//            }
//        }
//
//        try {
//            // 先在redis尝试插入值，返回值为0表示插入失败，其他表示插入成功
//            Long insert_ok = redisTemplate.opsForSet().add(today, info);
//            if (insert_ok != 0) {
//                // 插入成功
//                // redis插入成功，到备份表查询七天之内是否包含该条数据
//                String seven_days_ago = localDate.plusDays(-7).toString();
//                // 此处可将七天内的数据缓存到redis中，待修改
//                Integer log_count = tradeSysAgentMapper.selectUrlLog(info, seven_days_ago);
//                if (log_count == 0) {
//                    // 备份表中七天内没该数据，插入记录表中，同时到主表中插入
//                    tradeSysAgentMapper.InsertUrlLog(info, today);
//                    tradeSysAgentMapper.insertDouYingData(imei, idfa, oaid, oaid_md5, campaign_name, urlId, urlName, agentId, agentName);
//                }
//            }
//        } catch (NullPointerException e) {
//            // 如果redis插入有异常导致插入失败，直接查询备份表
//            Integer log_count = tradeSysAgentMapper.selectUrlLog(info, today);
//            if (log_count == 0) {
//                // 备份表中七天内没该数据，插入记录表中，同时到主表中插入
//                tradeSysAgentMapper.InsertUrlLog(info, today);
//                tradeSysAgentMapper.insertDouYingData(imei, idfa, oaid, oaid_md5, campaign_name, urlId, urlName, agentId, agentName);
//            }
//        }
////        tradeSysAgentMapper.insertDouYingData(imei, idfa, oaid, oaid_md5, campaign_name, urlId, urlName, agentId, agentName);
//    }
    @Override
    public void insertDouyingDatas(tiktokInfoDto dto, String info) {
        // 主要在这里操作redis缓存区，一共有八块缓存区，其中七块分别是前面七天每一天的缓冲块(数据类型是set)，还有一块tiktok_cache是主要存储全部数据的(数据类型是List)
        // 前七天的缓存区名字为当天日期
        LocalDate today = new LocalDate();
        String tiktok_cache = this.tiktok_cache;
        boolean fg = false;
        for (int i = 7; i >= 0; i--) {
            // 进行redis查询操作，检查前面的redis块是否有该元素
            LocalDate date = today.plusDays(-i);
            fg = cacheManager.sIsMember(date.toString() + "_tiktok", info);
            if (fg) break;// 如果有该元素，跳出循环，不存进 tiktok_cache
        }
        if (!fg) {
            // 如果缓存里面没有该数据，先存进今天的cache，再存进tiktok_cache
            cacheManager.sAdd(today.toString() + "_tiktok", info);
            // 构造JsonStr

            cacheManager.lLPush(tiktok_cache, dto);
        }
    }

    @Override
    public void insertShiPinHaoDatas(TencentInfoDto dto) {
        // 视频号链接
        // 该处主要操作redis缓存区，和tiktok操作一致
        LocalDate today = new LocalDate();
        String tencent_cache = this.tencent_cache;

        // 过滤空数据
        List<String> is_empty = new ArrayList<>();
        is_empty.add("");
        if (is_empty.contains(dto.getAndroid_id())
                && is_empty.contains(dto.getOaid())
                && is_empty.contains(dto.getMuid())) {
            // 全部数据为空
            return;
        }

        // 构造log
        String log = "urlName=" + dto.getUrlName() + "_";
        boolean fg = true; // 只要有一个设备标识有信息就可以了
        if (!is_empty.contains(dto.getMuid())) {
            log = log + "muid=" + dto.getMuid();
            fg = false;
        }
        if (!is_empty.contains(dto.getAndroid_id()) && fg) {
            log = log + "android=" + dto.getAndroid_id();
            fg = false;
        }
        if (!is_empty.contains(dto.getOaid()) && fg) {
            log = log + "oaid=" + dto.getOaid();
            fg = false;
        }
        if (!is_empty.contains(dto.getUser_agent()) && fg) {
            log = log + "userAgent=" + dto.getUser_agent();
        }

        cacheManager.lLPush(tiktok_cache, dto); // 先不进行过滤
        // 如果没有没有设备号区分，
//        if (fg) return;

        //  视频号接收不到数据，尝试先不进行过滤

        // 判断过去七天是否已经存在过该数据
//        boolean fg1 = false;
//        for (int i = 0; i <= 7; i++) {
//            LocalDate date = today.plusDays(-i);
//            fg1 = cacheManager.sIsMember(date.toString() + "_tencent", log);
//            if (fg1) break; // 如果有该元素，跳出循环，不存进 tencent_cache
//        }
//        if (!fg1) {
//            // 如果缓存里面没有该数据，先存进今天的cache，再存进tencent_cache
//            cacheManager.sAdd(today.toString() + "_tencent", log);
//            cacheManager.lLPush(tencent_cache, dto);
//        }
        // 尝试进行引用清理，防止内存泄漏
        is_empty.clear();
    }

    @Override
    public void insertBaiDuDatas(BaiDuInfoDto dto) {
        // 百度链接
        LocalDate today = new LocalDate();
        String baidu_cache = this.baiduCache;

        // 过滤空数据
        List<String> is_empty = new ArrayList<>();
        is_empty.add("");
        is_empty.add("");
        is_empty.add("__IDFA__");
        is_empty.add("__IMEI__");
        is_empty.add("__ANDROIDID1__");
        is_empty.add("__ANDROIDID__");
        is_empty.add("__MAC1__");
        is_empty.add("__MAC__");
        is_empty.add("__OAID__");
        is_empty.add("__OAID_MD5__");
        if (is_empty.contains(dto.getImei_md5())
                && is_empty.contains(dto.getAndroidid())
                && is_empty.contains(dto.getAndroidid_md5())
                && is_empty.contains(dto.getIdfa())
                && is_empty.contains(dto.getMac())
                && is_empty.contains(dto.getMac_md5())
                && is_empty.contains(dto.getOaid())
                && is_empty.contains(dto.getOaid_md5())) {
            // 全部标识为空
            return;
        }

        // 构造log
        String log = "urlName=" + dto.getUrlName() + "_";
        boolean fg = true; // 只要有一个设备标识有信息就可以了
        if (!is_empty.contains(dto.getImei_md5())) {
            log = log + "imeiMd5=" + dto.getImei_md5();
            fg = false;
        }
        if (!is_empty.contains(dto.getAndroidid()) && fg) {
            log = log + "androidId=" + dto.getAndroidid();
            fg = false;
        }
        if (!is_empty.contains(dto.getAndroidid_md5()) && fg) {
            log = log + "androidIdMd5=" + dto.getAndroidid_md5();
            fg = false;
        }
        if (!is_empty.contains(dto.getIdfa()) && fg) {
            log = log + "idfa=" + dto.getIdfa();
            fg = false;
        }
        if (!is_empty.contains(dto.getMac()) && fg) {
            log = log + "mac=" + dto.getMac();
            fg = false;
        }
        if (!is_empty.contains(dto.getMac_md5()) && fg) {
            log = log + "macMd5=" + dto.getMac_md5();
            fg = false;
        }
        if (!is_empty.contains(dto.getOaid()) && fg) {
            log = log + "oaid=" + dto.getOaid();
            fg = false;
        }
        if (!is_empty.contains(dto.getOaid_md5()) && fg) {
            log = log + "oaidMd5=" + dto.getOaid_md5();
        }

//        cacheManager.lLPush(baidu_cache, dto);// 先不进行过滤


        // 判断过去七天是否已经存在该数据
        boolean fg1 = false;
        for (int i = 0; i <= 7; i++) {
            LocalDate date = today.plusDays(-i);
            fg1 = cacheManager.sIsMember(date.toString() + "_baidu", log);
            if (fg1) break; // 如果有该元素，跳出循环，不存进 baidu_cache
        }

        if (!fg1) {
            // 如果缓存里面没有该数据，先存进今天的cache，再存进baidu_cache
            cacheManager.sAdd(today.toString() + "_baidu", log);
            cacheManager.lLPush(baidu_cache, dto);
        }
        is_empty.clear();
    }

    @Override
    public void insertKuaiShouDatas(KuaiShouInfoDto dto){
        // 快手链接
        LocalDate today = new LocalDate();
        String kuaishou_cache = this.kuaishouCache;

        //过滤空数据，暂不设置过滤

        // 构造log
//        String log = "urlName=" + dto.getUrlName() + "_";
//        boolean fg = true; // 只要有一个设备标识就可以了

        // 先直接存进去，不进行过滤操作
        cacheManager.lLPush(kuaishou_cache, dto);
    }


    /**
     * 抖音爬虫数据上传
     */
    @Override
    public void insertTiktokPlaywrightCommentLog(PlaywrightCommentLogDto playwrightCommentLogDto) {
        //爬取记录
        tradeSysAgentMapper.insertTiktokPlaywrightCommentLog(playwrightCommentLogDto);
    }

    @Override
    public void addTiktokPlaywrightUser(PlaywrightUserDto playwrightUserDto) {
        PlaywrightUserDto dto = tradeSysAgentMapper.selectPlaywrightUser(playwrightUserDto);
        if (dto != null) {
            tradeSysAgentMapper.updatePlaywrightUser(playwrightUserDto);
            return;
        }
        tradeSysAgentMapper.addTiktokPlaywrightUser(playwrightUserDto);
    }

    @Override
    public void addTiktokPlaywrightComment(PlaywrightCommentDto playwrightCommentDto) {
        tradeSysAgentMapper.InsertTiktokPlaywrightComment(playwrightCommentDto);
    }

    /**
     * 定期删除90天之前的过期信息
     */
    @Override
    public void deleteExpiredInfo() {
        tradeSysUserMapper.deleteExpiredInfo();
    }

    @Override
    public void deleteExpiredRedis() {
        LocalDate localDate = new LocalDate();
        String date = localDate.plusDays(-8).toString();
        cacheManager.del(date + "_tiktok");
        cacheManager.del(date + "_tencent");
    }

    @Override
    public void deleteExpiredUrlLog() {
        LocalDate localDate = new LocalDate();
        String date = localDate.plusDays(-7).toString();
        tradeSysAgentMapper.deleteExpiredUrlLog(date);
        tradeSysAgentMapper.deleteExpiredTencentUrlLog(date);
    }

    @Override
    public void handleInsertData() {
        // 将 redis 主缓存中的数据插入到数据库中，使用异步操作

        int total = this.total; // 每次处理的数据量
        handleAllDataAsync.asyncDataInsert(tiktok_cache, total);
        handleAllDataAsync.asyncTencentDataInsert(tencent_cache, total);
        handleAllDataAsync.asyncBaiduDataInsert(baiduCache, total);
        handleAllDataAsync.asyncKuaiShouDataInsert(kuaishouCache, total);
    }

    @Override
    public Result deleteUrl(TradeSysRoleDto tradeSysRoleDto) {
        Result result = new Result();
        try{
            tradeSysUserMapper.deleteUrl(tradeSysRoleDto);
            result.setCode(200);
        } catch (Exception e){
            result.setCode(400);
            result.setMessage("删除失败");
        }
        return result;
    }




}
